<template>
  <el-col :span="24">
    <div class="form-title-text-two" style="margin-bottom: 20px">
      {{ ['无'].includes(title) ? '' : title ? title : '案件情况' }}
    </div>
  </el-col>
  <el-col :span="24">
    <el-form-item v-if="show.indexOf('案情说明') !== -1" label="案情说明" prop="caseDesc">
      <!-- <div class="inline-edit-container">
        <div
          ref="caseDescRef"
          class="editable-text-area"
          :class="{ disabled: disabled || isFlow }"
          :contenteditable="disabled || isFlow ? 'false' : 'true'"
          @blur="handleTextChange">
          <span v-if="!caseIsEdit">
            <span v-for="(segment, index) in caseDescSegments" :key="index">
              <span v-if="segment.type === 'text'" v-html="segment.content" class="text-content"></span>
              <input
                v-else-if="segment.type === 'input'"
                v-model="segment.value"
                type="number"
                :placeholder="segment.placeholder"
                class="protected-input"
                contenteditable="false"
                @input="updateInlineInput(index)" />
            </span>
          </span>
          <span v-else>
            {{ form.caseDesc }}
          </span>
        </div>
        <textarea v-model="form.caseDesc" style="display: none" ref="hiddenTextarea"></textarea>
      </div> -->
      <el-input
        type="textarea"
        v-model="form.caseDesc"
        :disabled="disabled || isFlow"
        :rows="4"
        placeholder="请输入案情说明"></el-input>
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('检查情况') !== -1" :span="24">
    <!-- 检查情况 -->
    <el-form-item label="检查情况" prop="siteDescription">
      <SmartTextInput
        v-model="form.siteDescription"
        type="textarea"
        :rows="4"
        placeholder="请输入现场情况，输入关键词后按Tab键快速补全"
        :min-length="2"
        :max-suggestions="5"
        contentType="5" />
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('证据证明') !== -1" :span="24">
    <el-form-item label="证据证明" prop="evidenceDesc">
      <SmartTextInput
        v-model="form.evidenceDesc"
        type="textarea"
        :disabled="disabled || isFlow"
        :rows="4"
        placeholder="请输入证据证明"
        :min-length="2"
        :max-suggestions="5"
        contentType="100" />
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('违反条例') !== -1" :span="24">
    <el-form-item label="违反条例" prop="violationRegulations">
      <div class="inline-edit-container">
        <!-- 使用contenteditable的div作为大输入框 -->
        <div
          ref="violationRegulationsRef"
          class="editable-text-area"
          :class="{ disabled: disabled || violationDisabled }"
          :contenteditable="(disabled || isFlow) && violationDisabled ? 'false' : 'true'"
          @blur="handleTextChangeViolation"
          @input="handleTextInputViolation"
          @keydown="handleKeydownViolation">
          <!-- 动态渲染文本内容和日期输入框 -->
          <span v-if="!caseIsEdit || !violationIsEdit">
            <span v-for="(segment, index) in violationRegulationsSegments" :key="index">
              <span v-if="segment.type === 'text'" v-html="segment.content" class="text-content"></span>
              <input
                v-else-if="segment.type === 'input'"
                v-model="segment.value"
                type="number"
                :placeholder="segment.placeholder"
                class="protected-input"
                contenteditable="false"
                @input="updateViolationInput" />
            </span>
          </span>
          <span v-else>
            {{ form.violationRegulations }}
          </span>
        </div>
        <!-- 隐藏的textarea用于表单验证和数据绑定 -->
        <textarea v-model="form.violationRegulations" style="display: none" ref="hiddenTextarea"></textarea>
      </div>
      <!-- 智能匹配建议 -->
      <div v-if="showSuggestionsViolation && bestMatchViolation" class="suggestions-panel">
        <div class="suggestions-header">最佳匹配建议 (按Tab键补全)</div>
        <div
          v-for="(item, index) in bestMatchViolation"
          :key="index"
          :class="['suggestion-item', 'active']"
          @click="applySuggestionViolation(item)">
          <div class="suggestion-content" v-html="item.highlightedContent"></div>
          <div class="suggestion-similarity">匹配度: {{ Math.round(item.similarity * 100) }}%</div>
        </div>
      </div>
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('陈述申辩') !== -1" :span="24">
    <el-form-item label="陈述申辩" prop="statementDefense">
      <div class="inline-edit-container">
        <!-- 使用contenteditable的div作为大输入框 -->
        <div
          ref="statementDefenseRef"
          class="editable-text-area"
          :class="{ disabled: disabled || stateDisabled }"
          :contenteditable="(disabled || isFlow) && stateDisabled ? 'false' : 'true'"
          @blur="handleTextChange5"
          @input="handleTextInput5"
          @keydown="handleKeydown">
          <!-- 动态渲染文本内容和日期输入框 -->
          <span v-if="!caseIsEdit || !stateIsEdit">
            <span v-for="(segment, index) in statementDefenseSegments" :key="index">
              <span v-if="segment.type === 'text'" v-html="segment.content" class="text-content"></span>
              <input
                v-else-if="segment.type === 'input'"
                v-model="segment.value"
                type="number"
                :placeholder="segment.placeholder"
                class="protected-input"
                contenteditable="false"
                @input="updateStatementInput" />
            </span>
          </span>
          <span v-else>
            {{ form.statementDefense }}
          </span>
        </div>
        <!-- 隐藏的textarea用于表单验证和数据绑定 -->
        <textarea v-model="form.statementDefense" style="display: none" ref="hiddenTextarea"></textarea>
      </div>
      <!-- 智能匹配建议 -->
      <div v-if="showSuggestions5 && bestMatch" class="suggestions-panel">
        <div class="suggestions-header">最佳匹配建议 (按Tab键补全)</div>
        <div
          v-for="item in bestMatch"
          :key="item.id"
          :class="['suggestion-item', 'active']"
          @click="applySuggestion(item)">
          <div class="suggestion-content" v-html="item.highlightedContent"></div>
          <div class="suggestion-similarity">匹配度: {{ Math.round(item.similarity * 100) }}%</div>
        </div>
      </div>
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('处理依据') !== -1" :span="24">
    <el-form-item label="处理依据" prop="handlingBasis">
      <SmartTextInput
        v-model="form.handlingBasis"
        type="textarea"
        :disabled="disabled || isFlow"
        :rows="4"
        placeholder="请输入处理依据"
        :min-length="2"
        :max-suggestions="5"
        contentType="100" />
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('催告理由') !== -1" :span="24">
    <el-form-item label="催告理由" prop="reason">
      <div class="inline-edit-container">
        <!-- 使用contenteditable的div作为大输入框 -->
        <div
          ref="reasonRef"
          class="editable-text-area"
          :class="{ disabled: disabled || isFlow }"
          :contenteditable="disabled || isFlow ? 'false' : 'true'"
          @blur="handleTextChange3"
          @input="handleTextInputReason"
          @keydown="handleKeydownReason">
          <!-- 动态渲染文本内容和日期输入框 -->
          <span v-if="!isEdit">
            <span v-for="(segment, index) in reasonSegments" :key="index">
              <span v-if="segment.type === 'text'" v-html="segment.content" class="text-content"></span>
              <input
                v-else-if="segment.type === 'input'"
                v-model="segment.value"
                type="number"
                :placeholder="segment.placeholder"
                :disabled="reasonDisabled"
                class="protected-input"
                contenteditable="false"
                @input="updateReasonInput" />
            </span>
          </span>
          <span v-else>
            {{ form.reason }}
          </span>
        </div>
        <!-- 隐藏的textarea用于表单验证和数据绑定 -->
        <textarea v-model="form.reason" style="display: none" ref="hiddenTextarea"></textarea>
      </div>
      <!-- 智能匹配建议 -->
      <div v-if="showSuggestionsReason && bestMatchReason" class="suggestions-panel">
        <div class="suggestions-header">最佳匹配建议 (按Tab键补全)</div>
        <div
          v-for="(item, index) in bestMatchReason"
          :key="index"
          :class="['suggestion-item', 'active']"
          @click="applySuggestionReason(item)">
          <div class="suggestion-content" v-html="item.highlightedContent"></div>
          <div class="suggestion-similarity">匹配度: {{ Math.round(item.similarity * 100) }}%</div>
        </div>
      </div>
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('承办人意见') !== -1" :span="24">
    <el-form-item label="承办人意见" prop="handlerOpinion">
      <div class="inline-edit-container">
        <!-- 使用contenteditable的div作为大输入框 -->
        <div
          ref="handlerOpinionRef"
          class="editable-text-area"
          :class="{ disabled: disabled }"
          :contenteditable="disabled ? 'false' : 'true'"
          @blur="handleTextChange4"
          @input="handleTextInputOpinion"
          @keydown="handleKeydownOpinion">
          <!-- 动态渲染文本内容和日期输入框 -->
          <span v-if="!isEdit">
            <span v-for="(segment, index) in handlerOpinionSegments" :key="index">
              <span v-if="segment.type === 'text'" v-html="segment.content" class="text-content"></span>
              <input
                v-else-if="segment.type === 'input'"
                v-model="segment.value"
                type="number"
                :placeholder="segment.placeholder"
                class="protected-input"
                contenteditable="false"
                @input="updateHandlerOpinionInput" />
            </span>
          </span>
          <span v-else>
            {{ form.handlerOpinion }}
          </span>
        </div>
        <!-- 隐藏的textarea用于表单验证和数据绑定 -->
        <textarea v-model="form.handlerOpinion" style="display: none" ref="hiddenTextarea"></textarea>
      </div>
      <!-- 智能匹配建议 -->
      <div v-if="showSuggestionsOpinion && bestMatchOpinion" class="suggestions-panel">
        <div class="suggestions-header">最佳匹配建议 (按Tab键补全)</div>
        <div
          v-for="(item, index) in bestMatchOpinion"
          :key="index"
          :class="['suggestion-item', 'active']"
          @click="applySuggestionOpinion(item)">
          <div class="suggestion-content" v-html="item.highlightedContent"></div>
          <div class="suggestion-similarity">匹配度: {{ Math.round(item.similarity * 100) }}%</div>
        </div>
      </div>
    </el-form-item>
  </el-col>
  <el-col v-if="show.indexOf('处罚执行情况及罚没财物的处置情况') !== -1" :span="24">
    <el-form-item label="处罚执行情况及罚没财物的处置情况" prop="penaltyEnforcementDisposal">
      <div class="inline-edit-container">
        <!-- 使用contenteditable的div作为大输入框 -->
        <div
          ref="penaltyEnforcementDisposalRef"
          class="editable-text-area"
          :class="{ disabled: disabled }"
          :contenteditable="disabled ? 'false' : 'true'"
          @blur="handleTextChange6">
          <!-- 动态渲染文本内容和日期输入框 -->
          <span v-if="!penaltyIsEdit">
            <span v-for="(segment, index) in penaltyEnforcementDisposalSegments" :key="index">
              <span
                v-if="segment.type === 'text'"
                v-html="segment.content.replace(/\r\n/g, '<br>')"
                class="text-content"></span>
              <input
                v-else-if="segment.type === 'input'"
                v-model="segment.value"
                type="number"
                :placeholder="segment.placeholder"
                class="protected-input"
                contenteditable="false"
                @input="updatePenaltyEnforcementDisposalInput" />
            </span>
          </span>
          <span v-else>
            {{ form.penaltyEnforcementDisposal }}
          </span>
        </div>
        <!-- 隐藏的textarea用于表单验证和数据绑定 -->
        <textarea v-model="form.penaltyEnforcementDisposal" style="display: none" ref="hiddenTextarea"></textarea>
      </div>
    </el-form-item>
  </el-col>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed } from 'vue'
import useCompleteContent from '@/hooks/completeContent.js'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { commontermsGet } from '@/api/filingReview/register.js'

const props = defineProps({
  title: {
    type: String,
    default: '',
  },
  // 案件情况判断是否是编辑
  caseIsEdit: {
    type: Boolean,
    default: false,
  },
  // 陈述申辩告知是否是编辑
  stateIsEdit: {
    type: Boolean,
    default: false,
  },
  // 陈述申辩是否禁用
  stateDisabled: {
    type: Boolean,
    default: false,
  },
  // 违反条例是否是编辑
  violationIsEdit: {
    type: Boolean,
    default: false,
  },
  // 违反条例是否禁用
  violationDisabled: {
    type: Boolean,
    default: false,
  },
  // 催告理由是否禁用
  reasonDisabled: {
    type: Boolean,
    default: false,
  },
  // 催告理由和承办人意见判断是否是编辑
  isEdit: {
    type: Boolean,
    default: false,
  },
  // 处罚执行情况及罚没财物的处置情况是否是编辑
  penaltyIsEdit: {
    type: Boolean,
    default: false,
  },
  modelValue: {
    required: true,
    type: Object,
    default: () => ({}),
  },
  show: {
    type: String,
    default: '案情说明',
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否是流程页面
  isFlow: {
    type: Boolean,
    default: false,
  },
  // 罚款金额
  penaltyAmount: {
    type: [String, Number],
    default: '',
  },
  minLength: {
    type: Number,
    default: 2,
  },
  maxSuggestions: {
    type: Number,
    default: 5,
  },
})

const emit = defineEmits(['update:modelValue'])

const { parseReasonText, setCompleteContent } = useCompleteContent()

const form = computed({
  get: () => {
    return props.modelValue
  },
  set: val => {
    emit('update:modelValue', val)
  },
})

// 案情说明 复合框 start =====================================================
const caseDescRef = ref(null)
const caseDescSegments = ref([])
const isCreate3 = ref<Boolean>(true)
// watch(
//   () => [form.value.caseDesc],
//   newV => {
//     if (!newV || !isCreate3.value || props.show.indexOf('案情说明') === -1) {
//       return
//     }
//     // 初始化承办人意见文本（动态匹配）
//     console.log('案情说明初始化', newV, parseReasonText(newV))
//     caseDescSegments.value = parseReasonText(newV)
//     updateInlineInput()
//     isCreate3.value = false
//   }
// )
// 选择立案号后要带入检查情况
// const pullCaseDesc = () => {
//   console.log('复合框', caseDescSegments.value)
//   form.value.caseDesc = (form.value?.checkDesc || '') + form.value.caseDesc
//   // caseDescRef.value.innerText = form.value.caseDesc
//   caseDescSegments.value[0].content = form.value?.checkDesc || '' + caseDescSegments.value[0].content
//   console.log('pullCaseDesc', caseDescSegments.value, form.value.caseDesc)
// }

// 更新承办人意见输入
const updateInlineInput = () => {
  nextTick(() => {
    // 重新构建完整文本
    // let fullText = ''
    // handlerOpinionSegments.value.forEach(segment => {
    //   if (segment.type === 'text') {
    //     fullText += segment.content
    //   } else if (segment.type === 'input') {
    //     fullText += segment.value || segment.placeholder
    //   }
    // })
    // form.value.handlerOpinion = fullText
    handleTextChange()
  })
}

const handleTextChange = () => {
  nextTick(() => {
    if (props.caseIsEdit) {
      // 编辑模式下，直接使用纯文本
      const newText = caseDescRef.value.innerText
      form.value.caseDesc = newText
      // 重新解析文本并更新segments
      caseDescSegments.value = parseReasonText(`<span>${newText}</span>`)
    } else {
      // 新增模式下，获取混合内容并同步到segments
      form.value.caseDesc = setCompleteContent(caseDescRef.value, false)
    }
  })
}
// 案情说明 复合框 end =====================================================

// 检查情况 start =====================================================
// 选择立案号后要带入检查情况
const pullCaseDescOnly = () => {
  form.value.siteDescription = form.value.caseDesc
}
// 检查情况 end =====================================================

// 陈述申辩 复合框 start =====================================================
interface Article {
  content: string
  similarity?: number
  highlightedContent?: string
}
const statementDefenseRef = ref(null)
const statementDefenseSegments = ref([])
const isCreate4 = ref<Boolean>(true)
const showSuggestions5 = ref(false)
const suggestions = ref<Article[]>([])
// watch(
//   () => form.value.statementDefense,
//   newV => {
//     console.log('watch陈述申辩', newV, newV.length, isCreate4.value)
//     if (!newV || !isCreate4.value || props.show.indexOf('陈述申辩') === -1) {
//       statementDefenseRef.value.innerText = form.value.statementDefense
//       return
//     }
//     // 初始化陈述申辩文本（动态匹配）
//     console.log('陈述申辩初始化', parseReasonText(newV))
//     statementDefenseSegments.value = parseReasonText(newV)
//     updateStatementInput()
//     isCreate4.value = false
//   }
// )

// 更新陈述申辩输入
const updateStatementInput = () => {
  nextTick(() => {
    // 重新构建完整文本
    // let fullText = ''
    // handlerOpinionSegments.value.forEach(segment => {
    //   if (segment.type === 'text') {
    //     fullText += segment.content
    //   } else if (segment.type === 'input') {
    //     fullText += segment.value || segment.placeholder
    //   }
    // })
    // form.value.handlerOpinion = fullText
    handleTextChange5()
  })
}

const handleTextChange5 = () => {
  nextTick(() => {
    if (props.caseIsEdit && props.stateIsEdit) {
      // 编辑模式下，直接使用纯文本
      const newText = statementDefenseRef.value.innerText.trim()
      statementDefenseRef.value.innerText = newText
      form.value.statementDefense = newText
      // 重新解析文本并更新segments
      statementDefenseSegments.value = parseReasonText(`<span>${newText}</span>`)
    } else {
      // 新增模式下，获取混合内容并同步到 segments
      form.value.statementDefense = setCompleteContent(statementDefenseRef.value, false)
    }
  })
}

// 获取文章库
const getArticleDatabase = (content: string) => {
  return new Promise(async resolve => {
    const res = await commontermsGet({
      termType: 2,
      pageSize: 9999,
      pageNum: 1,
      status: 0,
      parentId: '',
      content: content,
    })
    if (res.data.length) {
      resolve(res.data)
    }
  })
}

// ==================== 通用模糊搜索函数 start ====================
// 处理文本输入和搜索
const handleTextInputSearch = async (
  value: string,
  suggestionsRef: Ref<Article[]>,
  showSuggestionsRef: Ref<boolean>
) => {
  if (!value || value.length < props.minLength) {
    showSuggestionsRef.value = false
    return
  }

  const database: any = await getArticleDatabase('同意') // value
  const matches = database
    .map((article: any) => ({
      ...article,
      similarity: calculateSimilarity('同意', article.content), // value
      highlightedContent: highlightKeywords(article.content, ['同意']), // value
    }))
    .filter((item: any) => item.similarity > 0.1)
    .sort((a: any, b: any) => b.similarity - a.similarity)
  suggestionsRef.value = matches
  showSuggestionsRef.value = matches.length > 0
}

// 处理键盘事件
const handleKeyboardEvent = (
  event: KeyboardEvent,
  showSuggestionsRef: Ref<boolean>,
  suggestionsRef: Ref<Article[]>,
  applyFn: (item: Article) => void,
  maxItems: number = props.maxSuggestions
) => {
  if (!showSuggestionsRef.value || suggestionsRef.value.length === 0) return

  switch (event.key) {
    case 'Tab':
    case 'Enter':
      if (suggestionsRef.value.length) {
        event.preventDefault()
        applyFn(suggestionsRef.value.slice(0, maxItems)[0])
      }
      break
    case 'Escape':
      showSuggestionsRef.value = false
      break
  }
}

// 计算最佳匹配项
const createBestMatchComputed = (suggestionsRef: Ref<Article[]>) => {
  return computed(() => {
    if (suggestionsRef.value.length === 0) return null
    return suggestionsRef.value.slice(0, props.maxSuggestions) || []
  })
}

// ==================== 计算文本相似度（简化版）
const calculateSimilarity = (str1: string, str2: string): number => {
  if (!str1 || !str2) return 0

  const text1 = str1.toLowerCase()
  const text2 = str2.toLowerCase()

  // 完全包含匹配
  if (text2.includes(text1)) return 0.9
  if (text1.includes(text2)) return 0.8

  // 关键词匹配
  const keywords1 = text1.split(/[\s，。！？；：、]+/).filter(k => k.length > 0)
  const keywords2 = text2.split(/[\s，。！？；：、]+/).filter(k => k.length > 0)

  let matches = 0
  for (const keyword of keywords1) {
    if (keyword.length < 2) continue
    if (keywords2.some(k => k.includes(keyword) || keyword.includes(k))) {
      matches++
    }
  }

  return matches / Math.max(keywords1.length, keywords2.length)
}
// 高亮匹配的关键词
const highlightKeywords = (text: string, keywords: string[]): string => {
  if (!keywords.length) return text

  let result = text
  keywords.forEach(keyword => {
    if (keyword.length >= 2) {
      const regex = new RegExp(`(${keyword})`, 'gi')
      result = result.replace(regex, '<mark class="highlight">$1</mark>')
    }
  })

  return result
}
// 最佳匹配项（只显示一个）
const bestMatch = computed(() => {
  if (suggestions.value.length === 0) return null
  return suggestions.value.slice(0, props.maxSuggestions) || []
})
// ==================== 通用模糊搜索函数 end ====================

// 文本输入处理
const handleTextInput5 = async () => {
  const value = setCompleteContent(statementDefenseRef.value, false) || statementDefenseRef.value?.innerText || ''
  await handleTextInputSearch(value, suggestions, showSuggestions5)
}

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  handleKeyboardEvent(event, showSuggestions5, suggestions, applySuggestion)
}

const applySuggestion = (item: Article) => {
  form.value.statementDefense = item.content
  statementDefenseRef.value.innerText = item.content
  showSuggestions5.value = false
}

// 陈述申辩 复合框 end =====================================================

// 违反条例 复合框 start =====================================================
const violationRegulationsRef = ref(null)
const violationRegulationsSegments = ref([])
const isCreateViolation = ref<Boolean>(true)
const showSuggestionsViolation = ref(false)
const suggestionsViolation = ref<Article[]>([])

// 更新违反条例输入
const updateViolationInput = () => {
  nextTick(() => {
    handleTextChangeViolation()
  })
}

const handleTextChangeViolation = () => {
  nextTick(() => {
    if (props.caseIsEdit && props.violationIsEdit) {
      // 编辑模式下，直接使用纯文本
      const newText = violationRegulationsRef.value.innerText.trim()
      violationRegulationsRef.value.innerText = newText
      form.value.violationRegulations = newText
      // 重新解析文本并更新segments
      violationRegulationsSegments.value = parseReasonText(`<span>${newText}</span>`)
    } else {
      // 新增模式下，获取混合内容并同步到 segments
      form.value.violationRegulations = setCompleteContent(violationRegulationsRef.value, false)
    }
  })
}

// 最佳匹配项
const bestMatchViolation = computed(() => {
  if (suggestionsViolation.value.length === 0) return null
  return suggestionsViolation.value.slice(0, props.maxSuggestions) || []
})

// 文本输入处理
const handleTextInputViolation = async () => {
  const value = setCompleteContent(violationRegulationsRef.value, false) || violationRegulationsRef.value?.innerText || ''
  await handleTextInputSearch(value, suggestionsViolation, showSuggestionsViolation)
}

// 键盘事件处理
const handleKeydownViolation = (event: KeyboardEvent) => {
  handleKeyboardEvent(event, showSuggestionsViolation, suggestionsViolation, applySuggestionViolation)
}

const applySuggestionViolation = (item: Article) => {
  form.value.violationRegulations = item.content
  violationRegulationsRef.value.innerText = item.content
  showSuggestionsViolation.value = false
}

// 违反条例 复合框 end =====================================================

// 催告理由 模糊搜索 start =====================================================
const suggestionsReason = ref<Article[]>([])
const showSuggestionsReason = ref(false)
const bestMatchReason = createBestMatchComputed(suggestionsReason)

const handleTextInputReason = async () => {
  const value = reasonRef.value?.innerText || ''
  await handleTextInputSearch(value, suggestionsReason, showSuggestionsReason)
}

const handleKeydownReason = (event: KeyboardEvent) => {
  handleKeyboardEvent(event, showSuggestionsReason, suggestionsReason, applySuggestionReason)
}

const applySuggestionReason = (item: Article) => {
  form.value.reason = item.content
  reasonRef.value.innerText = item.content
  showSuggestionsReason.value = false
}

// 催告理由 模糊搜索 end =====================================================

// 承办人意见 模糊搜索 start =====================================================
const suggestionsOpinion = ref<Article[]>([])
const showSuggestionsOpinion = ref(false)
const bestMatchOpinion = createBestMatchComputed(suggestionsOpinion)

const handleTextInputOpinion = async () => {
  const value = handlerOpinionRef.value?.innerText || ''
  await handleTextInputSearch(value, suggestionsOpinion, showSuggestionsOpinion)
}

const handleKeydownOpinion = (event: KeyboardEvent) => {
  handleKeyboardEvent(event, showSuggestionsOpinion, suggestionsOpinion, applySuggestionOpinion)
}

const applySuggestionOpinion = (item: Article) => {
  form.value.handlerOpinion = item.content
  handlerOpinionRef.value.innerText = item.content
  showSuggestionsOpinion.value = false
}

// 承办人意见 模糊搜索 end =====================================================

// 催告理由 动态匹配 start =====================================================
const reasonRef = ref(null)
const reasonSegments = ref([])
const isCreate = ref<Boolean>(true)
watch(
  () => form.value.reason,
  newV => {
    if (!newV || !isCreate.value) {
      return
    }
    // 初始化催告理由文本（动态匹配）
    reasonSegments.value = parseReasonText(newV)
    updateReasonInput()
    isCreate.value = false
  }
)

// 更新催告理由输入
const updateReasonInput = () => {
  nextTick(() => {
    // 重新构建完整文本
    // let fullText = ''
    // reasonSegments.value.forEach(segment => {
    //   if (segment.type === 'text') {
    //     fullText += segment.content
    //   } else if (segment.type === 'input') {
    //     fullText += segment.value || segment.placeholder
    //   }
    // })
    // form.value.reason = fullText
    handleTextChange3()
  })
}

const handleTextChange3 = () => {
  setTimeout(() => {
    if (props.isEdit) {
      // 编辑模式下，直接使用纯文本
      const newText = reasonRef.value.innerText.trim()
      reasonRef.value.innerText = newText
      form.value.reason = newText
      // 重新解析文本并更新segments
      reasonSegments.value = parseReasonText(`<span>${newText}</span>`)
    } else {
      // 新增模式下，获取混合内容并同步到segments
      form.value.reason = setCompleteContent(reasonRef.value, false)
    }
  }, 0)
}

// 催告理由 动态匹配 end =====================================================

// 承办人意见 动态匹配 start =====================================================
const handlerOpinionRef = ref(null)
const handlerOpinionSegments = ref([])
const isCreate2 = ref<Boolean>(true)
watch(
  () => form.value.handlerOpinion,
  newV => {
    if (!newV || !isCreate2.value || props.show.indexOf('承办人意见') === -1) {
      return
    }
    // 初始化承办人意见文本（动态匹配）
    newV = newV.replace(/XX/g, props.penaltyAmount)
    handlerOpinionSegments.value = parseReasonText(newV)
    updateHandlerOpinionInput()
    isCreate2.value = false
  }
)

// 更新承办人意见输入
const updateHandlerOpinionInput = () => {
  nextTick(() => {
    // 重新构建完整文本
    // let fullText = ''
    // handlerOpinionSegments.value.forEach(segment => {
    //   if (segment.type === 'text') {
    //     fullText += segment.content
    //   } else if (segment.type === 'input') {
    //     fullText += segment.value || segment.placeholder
    //   }
    // })
    // form.value.handlerOpinion = fullText
    handleTextChange4()
  })
}

const handleTextChange4 = () => {
  nextTick(() => {
    // if (props.isEdit) {
    //   if (!form.value.handlerOpinion && props.isEdit && isCreate2.value) {
    //     console.log('进2')
    //     // 如果初始化的时候没有值，编辑输入框后失焦后会出现重复的值，所以这里需要将重复的值清掉
    //     const spans = handlerOpinionRef.value.querySelectorAll('span')
    //     spans.forEach(span => {
    //       span.remove()
    //     })
    //     const text = handlerOpinionRef.value.innerText
    //     handlerOpinionRef.value.textContent = ''
    //     if (!!text.trim()) {
    //       spans[1].innerText = text
    //     }
    //     spans.forEach(span => {
    //       handlerOpinionRef.value.appendChild(span)
    //     })
    //     nextTick(() => {
    //       // handlerOpinionRef.value = parseReasonText(`<span>${handlerOpinionRef.value.innerText}</span>`)
    //       form.value.handlerOpinion = handlerOpinionRef.value.innerText
    //     })
    //   }
    // } else {
    //   // 新增模式下，获取混合内容并同步到segments
    //   form.value.handlerOpinion = setCompleteContent(handlerOpinionRef.value, false)
    // }
    if (props.isEdit) {
      // 编辑模式下，直接使用纯文本
      const newText = handlerOpinionRef.value.innerText
      form.value.handlerOpinion = newText
      // 重新解析文本并更新segments
      handlerOpinionSegments.value = parseReasonText(`<span>${newText}</span>`)
    } else {
      // 新增模式下，获取混合内容并同步到segments
      form.value.handlerOpinion = setCompleteContent(handlerOpinionRef.value, false)
    }
  })
}
// 承办人意见 动态匹配 end =====================================================

// 处罚执行情况及罚没财物的处置情况 动态匹配 start =====================================================
const penaltyEnforcementDisposalRef = ref(null)
const penaltyEnforcementDisposalSegments = ref([])
const isCreate5 = ref<Boolean>(true)
// watch(
//   () => form.value.penaltyEnforcementDisposal,
//   newV => {
//     if (!newV || !isCreate5.value) {
//       return
//     }
//     // 初始化处罚执行情况及罚没财物的处置情况文本（动态匹配）
//     penaltyEnforcementDisposalSegments.value = parseReasonText(newV)
//     updatePenaltyEnforcementDisposalInput()
//     isCreate5.value = false
//   }
// )

// 更新处罚执行情况及罚没财物的处置情况输入
const updatePenaltyEnforcementDisposalInput = () => {
  nextTick(() => {
    handleTextChange6()
  })
}

const handleTextChange6 = () => {
  nextTick(() => {
    if (props.penaltyIsEdit) {
      // 编辑模式下，直接使用纯文本
      const newText = penaltyEnforcementDisposalRef.value.innerText.trim()
      penaltyEnforcementDisposalRef.value.innerText = newText
      form.value.penaltyEnforcementDisposal = newText
      // 重新解析文本并更新segments
      penaltyEnforcementDisposalSegments.value = parseReasonText(`<span>${newText}</span>`)
    } else {
      // 新增模式下，获取混合内容并同步到segments
      form.value.penaltyEnforcementDisposal = setCompleteContent(penaltyEnforcementDisposalRef.value, false)
    }
  })
}
// 处罚执行情况及罚没财物的处置情况 动态匹配 end =====================================================

// 新增时初始化复合框
const handleInitInputs = (type = '') => {
  // if (!props.caseIsEdit) {
  //   form.value.caseDesc =
  //     '<span>我局于</span>XXXX<span>年</span>XX<span>月</span>XX<span>日对你单位上述行为进行立案调查。</span>'
  // }
  // if (!props.stateIsEdit) {
  //   form.value.statementDefense =
  //     '<span>我局于</span>XXXX<span>年</span>XX<span>月</span>XX<span>日以《行政处罚事先告知书》（兴环保监罚告字〔2025〕第XX号）告知该单位陈述申辩权，有《送达回证》为凭。该单位在法定期限内，未提出陈述申辩。</span>'
  // }
  if (type.indexOf('陈述申辩') !== -1) {
    // 初始化陈述申辩文本（动态匹配）
    statementDefenseSegments.value = parseReasonText(form.value.statementDefense)
    // updateStatementInput()
  }

  if (type.indexOf('违反条例') !== -1) {
    // 初始化违反条例文本（动态匹配）
    violationRegulationsSegments.value = parseReasonText(form.value.violationRegulations)
  }

  if (type.indexOf('处罚执行情况及罚没财物的处置情况') !== -1) {
    if (form.value.penaltyEnforcementDisposal && form.value.penaltyEnforcementDisposal.length > 0) {
      // 初始化处罚执行情况及罚没财物的处置情况文本（动态匹配）
      penaltyEnforcementDisposalSegments.value = parseReasonText(form.value.penaltyEnforcementDisposal)
      console.log('处罚执行情况及罚没财物的处置情况初始化', penaltyEnforcementDisposalSegments.value)
    }
  }
}
const handleInitInputs2 = () => {
  form.value.penaltyEnforcementDisposal =
    '<span>我局于</span>XXXX<span>年</span>XX<span>月</span>XX<span>日对你单位上述行为进行立案调查。</span>'
}

defineExpose({
  caseDescSegments,
  // pullCaseDesc,
  pullCaseDescOnly,
  statementDefenseSegments,
  violationRegulationsSegments,
  reasonSegments,
  handleTextChange,
  handleInitInputs,
  handleInitInputs2,
  parseReasonText,
  handlerOpinionSegments,
  penaltyEnforcementDisposalSegments,
})
</script>

<style scoped lang="scss">
.suggestions-panel {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  margin-top: 4px;
}

.suggestions-header {
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.suggestion-item {
  padding: 12px;
  border-bottom: 1px solid #999;
  cursor: pointer;
  transition: all 0.2s;
  margin: 5px 0;

  &:hover,
  &.active {
    background-color: #f5f7fa;
  }

  &:last-child {
    border-bottom: none;
  }
}

.suggestion-content {
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 6px;
}

.suggestion-similarity {
  font-size: 11px;
  color: #909399;
  text-align: right;
}

/* 高亮样式 */
:deep(.highlight) {
  background-color: #fff3cd;
  color: #856404;
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 500;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .suggestions-panel {
    max-height: 200px;
  }

  .suggestion-item {
    padding: 8px;
  }

  .suggestion-content {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    line-clamp: 2;
    overflow: hidden;
  }
}
</style>
